//
//  WSLoginViewController.swift
//  微校园
//
//  Created by Gao on 16/12/14.
//  Copyright © 2016年 weSchool. All rights reserved.
//

import UIKit
import SVProgressHUD

class WSLoginViewController: UIViewController , UIAlertViewDelegate {
    
    
    @IBOutlet weak var userNameField: UITextField!
    @IBOutlet weak var passwordField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()

    }

    /// 用户登录
    @IBAction func login(_ sender: UIButton) {
     
        // 获取用户名
        guard let contact = userNameField.text else {
            //提示手机号不能为空
            let alert = UIAlertView(title: "提示", message: "用户名不能为空", delegate: self, cancelButtonTitle: "确定", otherButtonTitles: "")
            alert.show()
            return
        }
        
        // 获取用密码
        guard var password = passwordField.text else {
            //提示密码不能为空
            let alert = UIAlertView(title: "提示", message: "密码不能为空", delegate: self, cancelButtonTitle: "确定", otherButtonTitles: "")
            alert.show()
            return
        }
        
        SVProgressHUD.show()
        
        password = RSAEncode.rsaEncrypotoTheData(password)
        
        // 参数封装
        var loginParmDic : [String: String]? = [String: String]()
        
        loginParmDic?["logonname"] = contact
        loginParmDic?["password"] = password
        loginParmDic?["deviceKbn"] = "1"
        loginParmDic?["model"] = UIDevice.current.model
        loginParmDic?["sdk"] = UIDevice.current.systemName
        
        WSNetworkManager.shared.login(URLString: WSLoginURL, parameters: loginParmDic as [String : AnyObject]?) { (result, isSuccess) in
            
            print(result ?? "")
            SVProgressHUD.dismiss()
            
            if isSuccess {
                //融云token
                //        guard let rongToken = WSNetworkManager.shared.userAccount?.token else {return}
                let rongToken : String = "xny2f4KREZoZDIvbmi489VJsM8sWxg1LHIvDjv5UFRbUbUT7wuqlDOOikWGDUTgQ5GG87uKlWrIUINhHVvBKew=="
                self.loginRongCloud(rongToken: rongToken)

            }
        }
        

        

        
        
    }

    
    
    

//        var result = responseObject
//        if (result["resultKbn"] == "0") {
//            var qiuManager = QiuManager.share()
//            if !XYString.isBlankString(result["result"]["token"]) {
//                qiuManager.token = result["result"]["token"]
//                GlobalMethod.userDefaultSetValue(result["result"]["token"], withKey: "token")
//                //登录成功，链接融云服务器
//                var manger = IMLibManager.share()
//                do {
//                    try manger.conectRongCloudServer(result["result"]["token"])
//                }
//                catch {
//                }
//            }
//            else {
//                //没有获取到融云的token
//                NoticeView.notice(withText: "连接服务器失败,请重试", target: GlobalMethod.getKeyWindow(), time: 1)
//                return
//        
//        ｝
//                //友盟统计
//                var mobManger = MobClickManager.share()
//                mobManger.accontStatistics(result["result"]["userSeq"], andLoginType: nil)
//                //保存一些数据。
//                qiuManager.userSeq = result["result"]["userSeq"]
//                qiuManager.antiStealingLinkKey = result["result"]["antiStealingLinkKey"]
//                qiuManager.headImageUrl = XYString.isNotNull(result["result"]["headImageUrl"])
//                //            [GlobalMethod userDefaultSetValue:@"1" withKey:@"QiuLogin"];
//                GlobalMethod.userDefaultSetValue(result["result"]["userSeq"], withKey: "QiuUserSeq")
//                GlobalMethod.userDefaultSetValue(result["result"]["antiStealingLinkKey"], with: "QiuAntiStealingLinkKey")
//                GlobalMethod.userDefaultSetValue(XYString.isNotNull(result["result"]["headImageUrl"]), withKey: "headImageUrl")
//                //不是第三方登录
//                qiuManager.isThirdParty = isNotThirdParty
//
//        
//    }
//
//            if (result["result"]["hasInterestArea"] == "1") {
//                //跳到我的注册页面
//                var controller = QiuSetNameSexViewController(nibName: "QiuSetNameSexViewController", bundle: nil)
//                self.navigationController!.pushViewController(controller, animated: true)
//            }
//            else {
//                var qiu = QiuTabBarViewController()
//                //                del.tabBarController=qiu;
//                GlobalMethod.changeRootViewController(qiu)
//            }
//
//            
//            self.passwordField.text = ""
//            NoticeView.notice(withText: result["errorMessage"], target: GlobalMethod.getKeyWindow(), time: 1)
//            
//            MBProgressHUD.hide(for: self.view, animated: true)
//            print("\(error)")
}


// MARK: - 链接融云服务器
fileprivate extension WSLoginViewController {
    
    func loginRongCloud(rongToken : String) {
        
        //连接融云服务器
        RCIM.shared().connect(withToken: rongToken,
                              success: { (userId) -> Void in
                                print("登陆成功。当前登录的用户ID：\(userId)")
                                
                                //设置当前登陆用户的信息
                                RCIM.shared().currentUserInfo = RCUserInfo.init(userId: userId, name: "我的名字", portrait: "http://www.rongcloud.cn/images/newVersion/logo/baixing.png")
                                
                                DispatchQueue.main.sync(execute: { () -> Void in
                                    // 登录成功后，展现WSMainViewController
                                    let vc = WSMainViewController()
                                    self.present(vc, animated: true, completion: nil)
                                    
                                    let transition = CATransition()
                                    transition.type = kCATransitionFade
                                    UIApplication.shared.keyWindow?.set(rootViewController: vc, withTransition: transition)
                                })
        }, error: { (status) -> Void in
            print("登陆的错误码为:\(status.rawValue)")
        }, tokenIncorrect: {
            //token过期或者不正确。
            //如果设置了token有效期并且token过期，请重新请求您的服务器获取新的token
            //如果没有设置token有效期却提示token错误，请检查您客户端和服务器的appkey是否匹配，还有检查您获取token的流程。
            print("token错误")
        })
    }
}

